define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var util = require('util');
	var dspUtil = require('dspUtil');

	var Base = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'class': 'P-AdExchangeWeight',
				'url': 'adexchange/weight',
				'view_model': {
					'data': []
				}
			});

			this.$id = null;
			this.Super('init', arguments);
		}
		,afterBuild:function(){
			this.append(`
				<div ms-repeat-adx="data" class="adx">
					<label>{{adx.Name}}:</label>
					<input ms-duplex="adx.value" type="text"/>
				</div>
			`);

			this.buildFromTemplate();
		}
		,load: function() {
			var c = this.getConfig();
			var vm = this.vm.$;
			var self = this;
			pubjs.mc.send(c.url, function(err, data) {
				if(err) {
					return pubjs.alert(err.message);
				}

				vm.data = self.formatAdx(data);
			});
		}
		,formatAdx: function(adx) {
			return dspUtil.map(adx, function(t) {
				t.value = '';
				return t;
			});
		}
		,empty: function() {
			this.changeField(null, true);
		}
		,changeField: function(field, empty) {
			var data = this.vm.$.data;
			data = dspUtil.map(data, function(t) {
				t.value = t.Weight.hasOwnProperty(field) && !empty ? String(t.Weight[field]) : '';
				return t;
			});
		}
		,validate: function(data){
			var vm = this.vm.$;
			return true;
		}
		,getData: function(){
			var self = this
				,vm = self.vm.$;

			var ret = [];
			for(var i = 0; i < vm.data.length; i++)
			{
				var tmp = vm.data[i];
				ret.push({AdxId: tmp.id, Value: +tmp.value || 0});
			}

			return ret;
		}
		,reset: function(){
			this.$id = 0;
			this.vm.reset();
			this.load();
			return this;
		}
	});

	exports.input = Base;

});